$(function() {

    function getId() {
        return location.hash.split("=")[1];
    }
    // console.log(getId())

    let res;

    function init() {

        res = $.ajax({
                url: "http://127.0.0.1:8888/goods/item/" + getId(),
                type: "get"
            })
            .done(function(res) {
                // console.log(res);
                renderPage(res);
            })
    }

    var small_img = document.querySelector(".jqzoom img");
    var detail = document.querySelector("#detail");
    var img_list = document.querySelectorAll("li img")
    var big_img = document.querySelector(".big-img img");
    var title = document.querySelector("#name h1");

    function renderPage(res) {

        console.log(res.info);


        small_img.src = res.info.img_big_logo;
        big_img.src = res.info.img_big_logo;
        img_list.src = res.info.img_big_logo;

        detail.innerHTML = res.info.goods_introduce;
        title.innerHTML = res.info.title;

    }
    $("#choose").on("click", ".btn-cart", handlerAdd);

    function handlerAdd() {
        var user_id = getCookie("userid");
        var goodsid = res.responseJSON.info.goods_id;
        var token = getCookie("token");
        console.log(res);
        // console.log($(this));//div#choose-btn-append.btn.btn-cart
        console.log(user_id, goodsid, token);


        var options = {
            url: `http://127.0.0.1:8888/cart/add?id=${user_id}&goodsId=${goodsid}`,
            type: "post",
            data: {
                id: user_id,
                goodsId: goodsid
            },
            headers: {
                authorization: token
            }

        }

        $.ajax(options)
            .done(function(data) {
                console.log(data);
                handlerAddData(data);
            })
    }


    function handlerAddData(data) {
        switch (data.code) {
            case 1:
                alert(data.message);
                break;

            case 401:
                alert("抱歉您还没有登录，请登录后再去加入购物车");
                location.href = "./login.html#goods";
                break;

        }
    }




    init();
})